﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using System.Text;
using Microsoft.Win32;

namespace SwordClient.SwordClientWebPart
{
    public class Utf8StringWriter : StringWriter
    {
        public override System.Text.Encoding Encoding
        {
            get
            {
                return Encoding.UTF8;
            }
        }
    }

    [ToolboxItemAttribute(false)]
    public class SwordClientWebPart : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/SwordClient/SwordClientWebPart/SwordClientWebPartUserControl.ascx";
        private const string _xsltPath = @"TEMPLATE/LAYOUTS/SwordClient/xslt/atom.xslt";

        const string c_SwordEndpointDefault = "";

        private string _swordendpoint;

        XslCompiledTransform _xsltAtomTransform;

        protected override void CreateChildControls()
        {
            SwordClientWebPartUserControl control = Page.LoadControl(_ascxPath) as SwordClientWebPartUserControl;
            Controls.Add(control);
            control.WebPart = this;

            // load the XSLT transform used to convert ADO.NET XML into Atom XML
            _xsltAtomTransform = new XslCompiledTransform();
            _xsltAtomTransform.Load(SPUtility.GetGenericSetupPath(_xsltPath));
        }

        [Personalizable(), WebBrowsable, WebDisplayName("Endpoint URL")]
        public string SwordEndpoint
        {
            get
            {
                return _swordendpoint;
            }
            set
            {
                _swordendpoint = value;
            }
        }

        public XslCompiledTransform XsltAtomTransform
        {
            get
            {
                return _xsltAtomTransform;
            }
            set
            {
                _xsltAtomTransform = value;
            }
        }

        public string GetMimeType(SPFile file)
        {
            string mimeType = "application/octet-stream";

            string ext = Path.GetExtension(file.Name);

            if (ext != null)
            {
                RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);

                if (regKey != null)
                {
                    object contentType = regKey.GetValue("Content Type");

                    if (contentType != null)
                    {
                        mimeType = contentType.ToString();
                    }
                }
            }

            return mimeType;
        }

        public XmlDocument GetItemXml(SPListItem item)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(item.Xml);

            XmlElement root = doc.DocumentElement;

            // add all field-values using their UUIDs
            foreach (SPField field in item.Fields)
            {
                if (field.Hidden)
                    continue;

                XmlElement node = doc.CreateElement("field");
                root.AppendChild(node);

                XmlAttribute name = doc.CreateAttribute("name");
                name.Value = field.InternalName;
                node.Attributes.Append(name);

                XmlAttribute id = doc.CreateAttribute("id");
                id.Value = field.Id.ToString();
                node.Attributes.Append(id);

                XmlAttribute value = doc.CreateAttribute("value");
                node.Attributes.Append(value);
                switch(field.Type)
                {
                    case SPFieldType.DateTime:
                        value.Value = SPFieldDateTime.GetFieldValueAsText((DateTime) item[field.Id], item.ParentList.ParentWeb, SPDateFormat.ISO8601);
                        break;
                    default:
                        value.Value = field.GetFieldValueForEdit(item[field.Id]);
                        break;
                }

                node.InnerText = field.GetFieldValueAsText(item[field.Id]);
            }

            return doc;
        }
    }
}
